<template>
  <div class="single-unit-maintenance-list-wrap">
    <el-row type="flex" justify="space-between" class="serach-form-wrap">
      <el-form class="serach-form" ref="searchForm" :model="searchForm" :inline="true" @submit.native.prevent>
        <el-form-item>
          <div class="iconfont icon-return return-btn" @click="returnFun" title="返回">{{ planName }}</div>
        </el-form-item>
        <el-form-item>
            <el-date-picker
                v-model="searchForm.time"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :picker-options="utils.intTimePickerOptions()"
                @change="search">
            </el-date-picker>
        </el-form-item>
        <el-form-item>
          <tree-select
            placeholder="请选择物联设备类别"
            v-model="searchForm.categoryIds"
            filterable
            :width="200"
            :data="typeList"
            :defaultProps="typeDefaultProps"
            :checkedKeys="defaultCheckedCategoryId"
            :nodeKey="typeNodeKey"
            @node-click="handleNodeClick">
          </tree-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable @change="search" v-model="searchForm.maintainType" placeholder="请选择维保类型">
            <el-option
                v-for="item in maintenanceTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select filterable @change="search" v-model="searchForm.workPeriod" placeholder="请选择维保周期">
            <el-option
                v-for="item in maintenanceCycleOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item class="small-select" label="状态：">
          <el-select @change="search" v-model="searchForm.status" placeholder="请选择">
            <el-option label="全部" value=""></el-option>
            <el-option label="未开始" value="0"></el-option>
            <el-option label="运行中" value="1"></el-option>
            <el-option label="停用" value="2"></el-option>
            <el-option label="过期" value="3"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button class="form-search-btn" type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row class="overclick-wrap" :gutter="40">
      <el-col :span="4">
        <div class="item-wrap" @click="searchForm.status=''" :class="searchForm.status==='' ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-4">{{ planStatistics.totalNum }}</p>
            <p class="item-title">计划总数（个）</p>
          </div>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.status='0'" :class="searchForm.status==='0' ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-8">{{ planStatistics.noStartedNum }}</p>
            <p class="item-title">未开始计划（个）</p>
          </div>  
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.status='1'" :class="searchForm.status==='1' ? 'active' : ''"> 
          <div class="item-content">
            <p class="item-value color-3">{{ planStatistics.underWayNum }}</p>
            <p class="item-title">运行中计划（个）</p>
          </div>  
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.status='2'" :class="searchForm.status==='2' ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-2">{{ planStatistics.noUseNum }}</p>
            <p class="item-title">停用计划（个）</p>
          </div>  
        </div>
      </el-col>
      <el-col :span="5">
        <div class="item-wrap" @click="searchForm.status='3'" :class="searchForm.status==='3' ? 'active' : ''">
          <div class="item-content">
            <p class="item-value color-1">{{ planStatistics.expireNum }}</p>
            <p class="item-title">过期计划（个）</p>
          </div>  
        </div>
      </el-col>
    </el-row>
    <div>
      <el-table
        v-loading="loading"
        ref="singleUnitTableList"
        :data="tableData"
        style="width: 100%">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="消防系统" prop="fireSystemName"></el-table-column>
        <el-table-column label="资产类别" prop="assetsCategoryName"></el-table-column>
        <el-table-column label="维保类型" prop="maintainTypeName"></el-table-column>
        <el-table-column label="维保周期" prop="workPeriod">
          <template slot-scope="scope">
            <div v-if="scope.row.workPeriod == 1">月</div>
            <div v-if="scope.row.workPeriod == 2">季</div>
            <div v-if="scope.row.workPeriod == 3">半年</div>
            <div v-if="scope.row.workPeriod == 4">年</div>
          </template>
        </el-table-column>
        <el-table-column label="维保公司" prop="companyName" width="300"></el-table-column>
        <el-table-column label="维保标准" prop="maintainStandardDesc" width="400">
          <template slot-scope="scope">
            <el-link class="maintain-standard" type="primary" @click="openMaintenanceStandard(scope.row)">{{scope.row.maintainStandardDesc}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template slot-scope="scope">
            <div v-if="scope.row.status === 0" class="type-tags type-color-8">未开始</div>
            <div v-else-if="scope.row.status === 1" class="type-tags type-color-3">运行中</div>
            <div v-else-if="scope.row.status === 2" class="type-tags type-color-2">停用</div>
            <div v-else class="type-tags type-color-1">过期</div>
          </template>
        </el-table-column>
        <el-table-column label="计划开始日期" prop="startTime" width="150" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="计划结束日期" prop="endTime" width="150" :formatter="formatDateTime"></el-table-column>
        <el-table-column label="操作" width="100" v-if="$store.state.buttonPermission[$store.state.currentTabName].indexOf('assetPlanManager') > -1">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status == 2" type="text" @click="enablePlan(scope.row)" size="small">启用</el-button>
            <el-button v-else-if="scope.row.status == 1 || scope.row.status == 0" @click="stopPlan(scope.row)" type="text" size="small">停用</el-button>
            <div v-else>-</div>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="[10, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 标准明细 -->
    <el-dialog
      :close-on-click-modal="false"
      title="维保标准"
      width="600px"
      top='10vh'
      :visible.sync="dialogMaintenanceStandard"
      @close="dialogMaintenanceStandard=false"
      v-dialogDrag>
        <div class="maintenance-standard-detail">
          <template v-for="(item, index) in standardDetailList">
            <p v-if="item != ''" :key="item.id">{{index+1}}、{{item}}。</p>
          </template>
        </div>
        <div class="more-btns">
            <el-button type="primary" @click="dialogMaintenanceStandard=false">好的</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import * as Dao from '@/api/assets'
import utils from '@/utils/util'

export default {
  name:'SingleUnitMaintenanceList',
  components: { 
    TreeSelect
  },
  props: {
    organizationId: {
      required: true
    },
    planName: {
      default () {
        return ''
      }
    },
    returnFun: {
        type: Function,
        default () {
            return ()=>{}
        }
    },
    planId: {
      default () {
        return ''
      }
    }
  },
  data() {
    return {
      utils: utils,
      loading: true,
      dialogMaintenanceStandard: false,
      searchForm: {
        time: '', // 计划时间
        fireSystemId: '', // 消防系统id
        categoryIds: '', // 消防系统树结构
        maintainType: '', // 维保类型
        workPeriod: '', // 维保周期
        status: '' // 状态
      },
      // 消防系统-资产类别
      typeList: [],
      typeDefaultProps: {
        children: 'categoryList',
        label: 'name',
        value: 'id'
      },
      typeNodeKey: 'id',
      defaultCheckedCategoryId: [],
      // 维保类型
      maintenanceTypeOptions: [{
        id: '',
        name: '全部维保类型' 
      },{
        id: 1,
        name: '维保巡查' 
      }, {
        id: 2,
        name: '保养' 
      }, {
        id: 3,
        name: '单点测试'  
      }, {
        id: 4,
        name: '联动测试' 
      }],
      // 维保周期
      maintenanceCycleOptions: [{
        id: '',
        name: '全部维保周期'
      }, {
        id: 1,
        name: '月'
      }, {
        id: 2,
        name: '季'
      }, {
        id: 3,
        name: '半年'
      }, {
        id: 4,
        name: '年'
      },],
      // 列表
      tableData: [],
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      planStatistics: {
        totalNum: 0, // 总数
        underWayNum: 0, // 进行中计划
        noStartedNum: 0, // 未开始计划
        expireNum: 0, // 过期计划
        noUseNum: 0 // 停用计划
      }, // 资产统计信息
      // 标准明细
      standardDetailList: []
    }
  },
  created() {
    this.getTypeList()
    this.getTableData()
  },
  methods: {
    getTypeList() {
      let that = this
      Dao.getAssetsCategoryIdWithAssets({
        orgId: that.organizationId
      }).then(res => {
        // 加上全部
        res.data.unshift({
          id: '',
          name: '全部物联设备类别'
        })
        that.typeList = res.data
        // 默认选择全部
        that.$nextTick(() => {
          that.defaultCheckedCategoryId = ['']
        })
      })
    },
    // 消防系统与设备类别树被点击
    handleNodeClick(obj, node, item) {
      let that = this
      if(obj.hasOwnProperty('fireSystemKey')) {
        // 记录系统id，不记录设备类别id
        that.searchForm.fireSystemId = obj.fireSystemKey
        that.searchForm.categoryIds = ''
      } else {
        // 不记录系统id，记录设备类别id
        that.searchForm.fireSystemId = ''
        that.searchForm.categoryIds = obj.id
      }
      that.search()
    },
    // 获取统计信息
    getStaticData() {
      // 获取多业主单位的统计信息
      Dao.statMaintainPlanDetail({
        startTime: this.searchForm.time && this.searchForm.time.length > 0 ? this.searchForm.time[0] + ' 00:00:00' : '',
        endTime: this.searchForm.time && this.searchForm.time.length > 0 ? this.searchForm.time[1] + ' 23:59:59' : '',
        orgIds: this.organizationId,
        fireSystemId: this.searchForm.fireSystemId || '',
        categoryIds: this.searchForm.categoryIds || '',
        maintainType: this.searchForm.maintainType || '',
        workPeriod: this.searchForm.workPeriod || '',
        planId: this.planId,
        status: ''
      }).then(res => {
          $.extend(this.planStatistics, res.data)
      })
    },
    // 获取列表数据
    getTableData(pageIndex, pageSize, isStatus) {
      let that = this
      that.loading = true
      if (pageIndex) {
        that.currentPage = pageIndex
      }
      if (pageSize) {
        that.pageSize = pageSize
      }
      let parames = {
        startTime: this.searchForm.time && this.searchForm.time.length > 0 ? this.searchForm.time[0] + ' 00:00:00' : '',
        endTime: this.searchForm.time && this.searchForm.time.length > 0 ? this.searchForm.time[1] + ' 23:59:59' : '',
        orgIds: that.organizationId,
        fireSystemId: that.searchForm.fireSystemId || '',
        categoryIds: that.searchForm.categoryIds || '',
        maintainType: that.searchForm.maintainType || '',
        workPeriod: that.searchForm.workPeriod || '',
        status: that.searchForm.status,
        planId: that.planId,
        pageSize: that.pageSize,
        pageIndex: that.currentPage - 1
      }
      Dao.getdailyPlanDetailsList(parames).then(res => {
        that.tableData = res.data
        that.total = res.total
        that.loading = false
      })

      if(!isStatus) {
        that.getStaticData()
      }
    },
    handleSizeChange(pageSize) {
      this.getTableData(1, pageSize, true)
    },
    handleCurrentChange(currentPage) {
      this.getTableData(currentPage, this.pageSize, true)
    },
    formatDateTime(row, column, cellValue, index) {
      if(cellValue) {
        return utils.ilinkTimeformat.format(new Date(cellValue), 'yyyy-MM-dd')
      } else {
        return '-'
      }
    },
    // 查询
    search() {
      this.getTableData(1)
    },
    // 打开维保标准
    openMaintenanceStandard(row) {
      let that = this

      that.standardDetailList = row.maintainStandardDesc.split('。')
      that.dialogMaintenanceStandard = true
      // Dao.getMaintainStandard({
      //   standardId: row.standardId
      // }).then(res => {
      //   that.standardDetailTitle = res.data.name
      //   that.standardDetailList = res.data.details
      //   that.dialogMaintenanceStandard = true
      // })
    },
    // 启用
    enablePlan(row) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      if (row) {
        this.$confirm('重新启用计划后，中间间隔时间的维保任务不会生成，从现在开始之后的维保任务按计划继续生成。', '提示', {
          confirmButtonText: '启用',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true
        }).then(() => {
          Dao.updatePlanDetailStatus({
            planDetailId: row.id,
            status: 1
          }).then(res => {
            if( res.status === 200) {
              that.$message({
                type: 'success',
                message: '启用成功!'
              })
              setTimeout(() => {
                this.currentPage = 0
                that.getTableData()
              }, 1000)
            } else {
              this.$message({
                type: 'warning',
                message: res.info
              })
            }
          })
          // 阻止事件冒泡
          event.stopPropagation()
        }).catch(() => {
          // this.$message({
          //     type: 'info',
          //     message: '已取消'
          // })
        })
      }
    },
    // 停用
    stopPlan(row) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      if (row) {
        this.$confirm('停用计划后，即不会生成新的维保任务。但之前的维保任务会继续执行。', '提示', {
          confirmButtonText: '停用',
          cancelButtonText: '取消',
          type: 'warning',
          roundButton: true
        }).then(() => {
          Dao.updatePlanDetailStatus({
            planDetailId: row.id,
            status: 2
          }).then(res => {
            if( res.status === 200) {
              that.$message({
                type: 'success',
                message: '停用成功!'
              })
              setTimeout(() => {
                this.currentPage = 0
                that.getTableData()
              }, 1000)
            } else {
              this.$message({
                type: 'warning',
                message: res.info
              })
            }
          })
          // 阻止事件冒泡
          event.stopPropagation()
        }).catch(() => {
        })
      }
    }
  },
  watch: {
    // categoryIdsSelect(val, oldVal) {
    //   if(val && val !== oldVal) {
    //     this.search()
    //   }
    // },
    maintenanceTypeSelect(val, oldVal) {
      if(val && val !== oldVal) {
        this.search()
      }
    },
    statusSelect(val, oldVal) {
        if(val !== oldVal) {
            this.getTableData(1, false, true)
        }
    }
  },
  computed: { 
    // categoryIdsSelect() {
    //   return this.searchForm.categoryIds
    // },
    maintenanceTypeSelect() {
      return this.searchForm.maintenanceType
    },
    statusSelect() {
      return this.searchForm.status
    }
  }
}
</script>
<style lang="scss">
.single-unit-maintenance-list-wrap {
    .serach-form-wrap {
        .el-form-item {
            margin-bottom: 0;
        }
        .small-select {
            .el-form-item__content {
                width: 120px;
            }
        }
    } 
    .more-btns {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 20px;
        padding-right: 20px;
        .el-dropdown {
            padding: 0 10px;
            height: 38px;
            line-height: 38px;
            border: 1px solid #409EFF;
            border-radius: 3px;
        }
    }
    .maintain-standard {
      width: 100%;
      .el-link--inner {
        width: 100%;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
      }
    }
    .maintenance-standard-detail {
        margin-bottom: 25px;
        p {
            line-height: 28px;
            margin-bottom: 15px;
        }
    }
}

</style>
